package org.swimv2.servlets;

import java.io.IOException;
import java.util.List;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.swimv2.entities.Job;
import org.swimv2.entities.Skill;
import org.swimv2.entities.User;
import org.swimv2.interfaces.AccessManagerRemote;
import org.swimv2.interfaces.FriendshipManagerRemote;
import org.swimv2.interfaces.JobsManagerRemote;
import org.swimv2.interfaces.SkillManagerRemote;
import org.swimv2.utils.ContextUtil;

/**
 * Gestisce il login di User (e quindi anche di Admin).
 * 
 * @author Lorenzo Delledonne
 */
public class LoginServlet extends HttpServlet {
	
	private static final long serialVersionUID = -7419935089593893820L;

	private User u = null;
	
	private AccessManagerRemote       mgr_u = null;
	private FriendshipManagerRemote   mgr_f = null;
	private JobsManagerRemote         mgr_j = null;
	private SkillManagerRemote        mgr_s = null;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * Riceve una richiesta compilata con le credenziali di un utente registrato (email e password),
	 * verifica tali credenziali e in caso di esito positivo inizializza il sistema e reindirizza il
	 * browser dell'utente/amministratore sulla pagina "Profilo" corrispondente.  
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		String par_email = request.getParameter("email");
		String par_passw = request.getParameter("password");
		
		try {
			Context ctx = ContextUtil.getInitialContext();
			mgr_u = (AccessManagerRemote) ctx.lookup("AccessManagerJNDI");
			mgr_f = (FriendshipManagerRemote) ctx.lookup("FriendshipManagerJNDI");
			mgr_j = (JobsManagerRemote)         ctx.lookup("JobsManagerJNDI");
			mgr_s = (SkillManagerRemote)        ctx.lookup("SkillManagerJNDI");
			
			u = mgr_u.validate_login(par_email, par_passw);
			
			RequestDispatcher disp;
			
			/* Login non effettuato. */
			if (u == null) {
				request.setAttribute("error_message", "Errore: email o password non validi.");
				disp = request.getRequestDispatcher("access/login.jsp");
				
			/* Login effettuato. Distinzione tra User e Admin. */
			} else {
				request.getSession().setAttribute("user", u);
				// Admin session
				if ( u.getIsAdmin() ) {
					request.setAttribute("message", "Login effettuato (Admin).");
					disp = request.getRequestDispatcher("admin/profile.jsp");
				// User session
				} else {
					request.setAttribute("message", "Login effettuato (User).");
					addToRequestProfile(request);
					disp = request.getRequestDispatcher("user/profile.jsp");
				}
			}
			/* Redirect sulla pagina profilo */
			disp.forward(request, response);
			
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	
	/**
	 * Aggiunge alla HTTP Request i parametri necessari a user/profile.jsp
	 * per la visualizzazione del profilo dell'utente loggato.
	 * 
	 * @param request
	 */
	protected void addToRequestProfile(HttpServletRequest request) {
		request.setAttribute("active_skills", (List<Skill>) mgr_s.listAllActiveSkills());
		request.setAttribute("curr_user_skills", (List<Skill>) mgr_s.listUserSkills(u));
		request.setAttribute("curr_user_jobs", (List<Job>) mgr_j.listJobsWork(u));
		request.setAttribute("curr_user_friendreqsusers", (List<User>) mgr_f.listFriendshipReq(u));
	}
}
